package pri.black.dogview.util;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pri.black.dogview.exception.BizException;

import java.io.IOException;

public class ViewResolver {
    public static void resolve(HttpServletRequest request, HttpServletResponse response) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 405);
            jsonObject.put("msg", "not permittted");
            response.setStatus(403);
            String youAreNotAllowed = jsonObject.toJSONString();
            response.setContentLength(youAreNotAllowed.getBytes().length);
            response.setContentType("application/json");
            response.getOutputStream().print(youAreNotAllowed);
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void resolveError(HttpServletRequest request, HttpServletResponse response) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("msg", "error");
            response.setStatus(500);
            String youAreNotAllowed = jsonObject.toJSONString();
            response.setContentLength(youAreNotAllowed.getBytes().length);
            response.setContentType("application/json");
            response.getOutputStream().print(youAreNotAllowed);
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void resolveError(HttpServletRequest request, HttpServletResponse response, BizException exception) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("msg", exception.getMessage());
            response.setStatus(403);
            String youAreNotAllowed = jsonObject.toJSONString();
            response.setContentLength(youAreNotAllowed.getBytes().length);
            response.setContentType("application/json");
            response.getOutputStream().print(youAreNotAllowed);
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
